import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:get/get.dart';
import 'package:xiaomi_shop/app/api/api.dart';
import 'package:xiaomi_shop/app/services/screenAdapter.dart';
import 'package:xiaomi_shop/app/services/signService.dart';
import 'package:xiaomi_shop/app/services/userService.dart';
import 'package:xiaomi_shop/app/services/xhttp.dart';
import 'package:xiaomi_shop/models/index.dart';
import 'package:xiaomi_shop/models/userModel.dart';

class RefreshListView extends StatefulWidget {
  String url;
  Map argument;
  void Function(OrderModel model)? onTap;
  RefreshListView(
      {required this.url, required this.argument, this.onTap, super.key});

  @override
  State<RefreshListView> createState() => _RefreshListViewState();
}

class _RefreshListViewState extends State<RefreshListView> {
  var datasource = [].obs;
  var page = 0;
  late EasyRefreshController refreshController;

  @override
  void initState() {
    super.initState();
    refreshController = EasyRefreshController(
        controlFinishLoad: true, controlFinishRefresh: true);
    loadData(widget.url, widget.argument);
  }

  @override
  void dispose() {
    super.dispose();
    refreshController.dispose();
  }

  loadData(String url, Map tempJson) async {
    print("argument ${widget.argument}");
    UserModel? user = await UserService.getUser();
    Map param = {
      ...tempJson,
      "uid": user?.id,
    };
    // 获取签名
    String sign = SignService.sign({...param, "salt": user?.salt});
    var response = await XHttp.getInstance().get(url, {...param, "sign": sign});
    if (response != null) {
      Result result = response as Result;
      if (result.data["result"] != null) {
        List list = result.data["result"];
        datasource.addAll(list.map((e) => OrderModel.fromJson(e)).toList());
        refreshController.finishLoad(list.length < 10
            ? IndicatorResult.noMore
            : IndicatorResult.success);
        refreshController.finishRefresh();
      } else {
        Toast.show(result.msg, type: Toast.ERROR);
        refreshController.finishLoad();
        refreshController.finishRefresh();
      }
    } else {
      Toast.show("网络错误", type: Toast.ERROR);
      refreshController.finishLoad();
      refreshController.finishRefresh();
    }
  }

  onRefresh() {
    page = 0;
    datasource.clear();
    loadData(widget.url, widget.argument);
    refreshController.resetFooter();
  }

  onLoadMore() {
    page++;
    loadData(widget.url, widget.argument);
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.grey.shade100,
      child: EasyRefresh(
          controller: refreshController,
          onLoad: onLoadMore,
          onRefresh: onRefresh,
          child: Obx(() => ListView.builder(
                itemCount: datasource.value.length,
                itemBuilder: (context, index) {
                  OrderModel model = datasource.value[index];
                  return InkWell(
                      onTap: () {
                        widget.onTap!(model);
                      },
                      child: Card(
                        margin: EdgeInsets.all(ScreenAdapter.width(30)),
                        color: Colors.white,
                        elevation: 0,
                        child: Padding(
                          padding: EdgeInsets.all(ScreenAdapter.width(30)),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                "订单编号：${model.order_id}",
                                style: TextStyle(
                                    fontSize: ScreenAdapter.fontSize(44)),
                              ),
                              SizedBox(
                                height: ScreenAdapter.height(30),
                              ),
                              // 商品
                              Container(
                                margin: EdgeInsets.only(
                                    top: ScreenAdapter.height(20),
                                    bottom: ScreenAdapter.height(20)),
                                child: Column(
                                  children: model.order_item!.map((e) {
                                    OrderItemModel itemModel = e;
                                    return Column(
                                      children: [
                                        Row(children: [
                                          SizedBox(
                                            width: ScreenAdapter.width(160),
                                            height: ScreenAdapter.width(160),
                                            child: Image.network(
                                              "${Api.basicUrl}/${itemModel.product_img}",
                                              fit: BoxFit.cover,
                                            ),
                                          ),
                                          SizedBox(
                                            width: ScreenAdapter.width(20),
                                          ),
                                          Expanded(
                                            child:
                                                Text(itemModel.product_title!),
                                          ),
                                          Text("x${itemModel.product_count}")
                                        ]),
                                        SizedBox(
                                          height: ScreenAdapter.height(20),
                                        )
                                      ],
                                    );
                                  }).toList(),
                                ),
                              ),
                              // 合计
                              Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  Text.rich(TextSpan(
                                      text: "合计：",
                                      style: const TextStyle(
                                          fontWeight: FontWeight.w500),
                                      children: [
                                        TextSpan(
                                            text: "¥${model.all_price}",
                                            style: TextStyle(
                                                color: Colors.orange.shade900,
                                                fontWeight: FontWeight.w500))
                                      ])),
                                  ElevatedButton(
                                      style: ButtonStyle(
                                          elevation:
                                              const MaterialStatePropertyAll(0),
                                          backgroundColor:
                                              MaterialStatePropertyAll(
                                                  Colors.grey.shade300),
                                          foregroundColor:
                                              const MaterialStatePropertyAll(
                                                  Colors.black54),
                                          shape: MaterialStatePropertyAll(
                                              RoundedRectangleBorder(
                                                  borderRadius:
                                                      BorderRadius.circular(
                                                          8)))),
                                      onPressed: () {},
                                      child: Text("申请售后"))
                                ],
                              )
                            ],
                          ),
                        ),
                      ));
                },
              ))),
    );
  }
}
